#Include "Protheus.ch"
#Include "TopConn.ch"
#Include "TbiConn.ch"

User Function AtualSF2()

Local cQuery    := ""
Local cAlias    := GetNextAlias()

Local nRecCount := 0

RpcSetType(3)
PREPARE ENVIRONMENT EMPRESA "01" FILIAL "01"

cQuery += " SELECT DISTINCT C6_NOTA, C6_SERIE, C5_BONIF" + CRLF
cQuery += " FROM " + RetSqlTab("SC5") + CRLF
cQuery += 	" INNER JOIN " + RetSqlTab("SC6") + CRLF
cQuery += 		" ON C5_NUM = C6_NUM" + CRLF
cQuery += " WHERE C5_VEND1 = '250'" + CRLF
cQuery += 	" AND C6_NOTA > '0' AND C5_BONIF > '0'" + CRLF
cQuery += 	" AND " + RetSqlFil("SC5,SC6") + CRLF
cQuery += 	" AND " + RetSqlDel("SC5,SC6") + CRLF
cQuery += " ORDER BY C6_NOTA, C6_SERIE"

cQuery := ChangeQuery(cQuery)

TCQUERY cQuery NEW ALIAS &cAlias

Count To nRecCount

IF nRecCount > 0

	(cAlias)->(dbGoTop())
	SF2->(dbSetOrder(1))
	
	While (cAlias)->(!Eof())
	
		IF SF2->(dbSeek(xFilial("SF2") + (cAlias)->C6_NOTA + (cAlias)->C6_SERIE))
		
			RecLock("SF2", .F.)
				
				SF2->F2_BONIFIC := (cAlias)->C5_BONIF
				
			MsUnlock()
		
		EndIF
	
		(cAlias)->(dbSkip())
	
	EndDo

EndIF

(cAlias)->(dbCloseArea())

RESET ENVIRONMENT

Return Nil